//
//  TweetDetailViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-12.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "TweetDetailViewController.h"

#import "ViewControllerChooser.h"
#import "ReplyTweetViewController.h"
#import "UserInfoViewController.h"

#import "TwitterClient.h"


@implementation TweetDetailViewController

@synthesize tweet;
@synthesize entry;
//@synthesize btnReply;
//@synthesize btnFav;
@synthesize txtTweet;
@synthesize tws;
@synthesize profileImageView;
@synthesize lblName;
@synthesize lblDescript;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
											[NSArray arrayWithObjects:
											 [UIImage imageNamed:@"up.png"],
											 [UIImage imageNamed:@"down.png"],
											 nil]];
	[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
	segmentedControl.frame = CGRectMake(0, 0, 90, kCustomButtonHeight);
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
	segmentedControl.momentary = YES;
	
	defaultTintColor = [segmentedControl.tintColor retain];	// keep track of this for later
	
	UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
    [segmentedControl release];
    
	self.navigationItem.rightBarButtonItem = segmentBarItem;
    [segmentBarItem release];
	
	NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
	[center addObserver:self selector:@selector(processRequest:) name:@"RECV_TUITE" object:nil];
}
	
- (void)viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	NSString *tt;
	if(self.tweet){
		tt = self.tweet.usr.name;
	}else{
		tt = @"Detail";
	}
	self.tabBarController.navigationItem.title = tt;
	if(self.tweet){
		[self reloadInfo:self];
	}else{
		// tt = @"";
		index = 0;
	}	
	// txtTweet.text = tt;
	// lblTweet.text = tt;
}

- (void)viewDidDisappear:(BOOL)animated{
	[super viewDidDisappear:animated];
}



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	self.tweet = nil;
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.tweet = nil;
	self.txtTweet = nil;
//	self.btnRT = nil;
//	self.btnReply = nil;
//	self.btnFav = nil;
	self.profileImageView = nil;
	self.lblName = nil;
	self.lblDescript = nil;
	[tws release];
}

#pragma mark -
#pragma mark RT Tweet
- (IBAction)rtTweet:(id)sender{
	//ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
//	ReplyTweetViewController *rtvc = (ReplyTweetViewController *)[chooser choose:VC_REPLY_TWEET];
//	rtvc.tweet = self.tweet;
//	rtvc.acType = AC_TYPE_RT;
//	[self.navigationController pushViewController:rtvc animated:YES];
	
	NSMutableDictionary *params = [NSMutableDictionary dictionary];
	[params setObject:self.tweet.tid forKey:@"tt_id"];
	[NSThread detachNewThreadSelector:@selector(sendRT:) toTarget:self withObject:params];
}

- (void)sendRT:(NSDictionary *)args{
	TwitterClient *client = [TwitterClient getInstance];
	[client doStatusesRetweet:args];
}

#pragma mark -

- (IBAction)replyTweet:(id)sender{
	ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
	ReplyTweetViewController *rtvc = (ReplyTweetViewController *)[chooser choose:VC_REPLY_TWEET];
	rtvc.tweet = self.tweet;
	rtvc.acType = AC_TYPE_REPLY;
	[self.navigationController pushViewController:rtvc animated:YES];
}

- (IBAction)segmentAction:(id)sender
{
	// The segmented control was clicked, handle it here 
	// TODO 处理点击事件用于显示上一条，下一条
	UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
	//NSLog(@"Segment clicked: %d", segmentedControl.selectedSegmentIndex);
	NSInteger si = segmentedControl.selectedSegmentIndex;
	BOOL load = NO;
	if(si == 0){
		// TODO 上一条
		if(index == 0){
			[segmentedControl setEnabled:NO forSegmentAtIndex:0];
		}else{
			index--;
			self.tweet = [tws objectAtIndex:index];
			load = YES;
			if([segmentedControl isEnabledForSegmentAtIndex:1] == NO){
				[segmentedControl setEnabled:YES forSegmentAtIndex:1];
			}
		}
	}else{
		// TODO 下一条
		if(index == [tws count] - 1){
			[segmentedControl setEnabled:NO forSegmentAtIndex:1];
		}else{
			index++;
			self.tweet = [tws objectAtIndex:index];
			load = YES;
			if([segmentedControl isEnabledForSegmentAtIndex:0] == NO){
				[segmentedControl setEnabled:YES forSegmentAtIndex:0];
			}
		}
	}
	
	if(load){
		[self performSelectorOnMainThread:@selector(reloadInfo:) withObject:nil waitUntilDone:NO];
	}	
}

- (void)reloadInfo:(id)sender{
	NSString *tt;
	if(self.tweet){
		tt = self.tweet.usr.name;
		self.navigationItem.title = tt;
		tt = self.tweet.text;
		tweet.unreaded = [NSNumber numberWithBool:NO];
		index = [tws indexOfObject:tweet];
		
		self.lblName.text = tweet.usr.name;
		self.lblDescript.text = tweet.created_at;
		ProfileImageProcesser *pp = [ProfileImageProcesser getInstance];
		UIImage *img = [pp getImage:tweet.usr.profile_image_url];
		if(img){
			self.profileImageView.image = img;
		}else{
			// TODO 使用默认内容
			self.profileImageView.image = pp.deflogo;
		}
		NSMutableString *s8 = [[NSMutableString alloc] init];
		NSInteger len = [tt length];
		NSInteger start = 0, end;
		NSRange rg,rg1,rg2;
		[s8 appendFormat:@"<html><body>"];
		while(start < len){
			rg = [tt rangeOfString:@"@" options:NSCaseInsensitiveSearch range:NSMakeRange(start, (len - start))];
			if(rg.location == NSNotFound){
				[s8 appendString:[tt substringWithRange:NSMakeRange(start, (len - start))]];
				break;
			}
			[s8 appendString:[tt substringWithRange:NSMakeRange(start, (rg.location - start))]];
			start = rg.location;
			rg1 = [tt rangeOfString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(start, (len - start))];
			rg2 = [tt rangeOfString:@":" options:NSCaseInsensitiveSearch range:NSMakeRange(start, (len - start))];
			if(rg1.location != NSNotFound){
				if(rg2.location != NSNotFound){
					if(rg1.location < rg2.location){
						end = rg1.location;
					}else{
						end = rg2.location;
					}
				}else{
					end = rg1.location;
				}
			}else if(rg2.location != NSNotFound){
				end = rg2.location;
			}else{
				end = len;
			}
			NSString *uid = [tt substringWithRange:NSMakeRange(start+1, (end - start - 1))];

			[s8 appendString:@"<a href=\"tuite://user/show?"];
			
			[s8 appendString:uid];
			[s8 appendString:@"\">"];
			[s8 appendString:@"@"];
			[s8 appendString:uid];
			[s8 appendString:@"</a>"];
			start = end;
		}
		[s8 appendString:@"</body></html>"];
		[self.txtTweet loadHTMLString:s8 baseURL:nil];
		[s8 release];
	}
	//else{
//		tt = @"Detail";
//	}	
}


#pragma mark -
#pragma mark tuite:// process

- (void)processRequest:(NSNotification *)arg{
	id aa = [arg object];
	if([aa isKindOfClass:[NSURL class]]){
		NSURL *url = (NSURL *)aa;
		// TODO 处理请求
		//NSLog(@"%@",url);
		//NSLog(@"host %@",[url host]);
		//NSLog(@"path %@",[url path]);  // like /show
		//NSLog(@"query %@",[url query]); // query value dosn't include ?
		NSString *cat = [url host];
		NSString *mth = [url path];
		NSString *value = [url query];
		if([cat isEqualToString:@"user"]){
			if([mth isEqualToString:@"/show"]){
				UserInfoViewController *userinfo = (UserInfoViewController *)[[ViewControllerChooser sharedChooser] choose:VC_USER_INFO];
				userinfo.username = value;
				[self.navigationController pushViewController:userinfo animated:YES];
			}
		}
	}
}

#pragma mark -

- (void)dealloc {
	[tweet release];
	[entry release];
	[tws release];
    [super dealloc];
}


@end
